/* logger.c
 * Save a tree, climb a lumberjack instead.
 * ratbox-montor
 *
 * Copyright (C) 2011-2012 Dan Reidy <dubkat@ratbox.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *
 *       Foundation, Inc.
 *       59 Temple Place - Suite 330
 *       Boston, MA  02111-1307, USA.
 *
 *
 * $Id: logger.c 44 2012-04-02 18:05:46Z dubkat $
 */

#include <time.h>
#include "ratbox_lib.h"
#include "common.h"
#include "libconfig.h"
#include "logger.h"

extern config_t conf;

void
logger(int level, const char *format, ...)
{
	struct status *me = &my_status;

	FILE *fd;
	va_list args;
	char *string;
	const char *logfile;
	int loglevel;

	time_t now = time(NULL);
	struct tm *t = localtime(&now);
	int size = (IRCD_BUFSIZE * sizeof(char));

	if ( !me->foreground ) {
		config_lookup_string(&conf, "general.logfile", &logfile);
		config_lookup_int(&conf, "general.loglevel", &loglevel);

		if(loglevel == NONE)
			return;
	}

	if(loglevel >= level)
	{
		if ( !me->foreground ) {
			fd = fopen(logfile, "a");
			if(fd == NULL)
			return;
		}

		if((string = rb_malloc(size)) == NULL)
		{
			fprintf(me->foreground ? stdout : fd, "ERROR: OUT OF MEMORY IN log!\n");
			exit(EXIT_FAILURE);
		}

		va_start(args, format);
		vsnprintf(string, size, format, args);
		va_end(args);
		fprintf(me->foreground ? stdout : fd, "[%04d-%02d-%02d %02d:%02d:%02d] %s\n",
			t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
			t->tm_hour, t->tm_min, t->tm_sec, string);

		if ( !me->foreground )
			fclose(fd);

		rb_free(string);
	}
}
